package org.jeecg.modules.demo.teacher.controller;

import cn.hutool.core.date.DateTime;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.modules.demo.constant.BaseContext;
import org.jeecg.modules.demo.constant.papersStatus;
import org.jeecg.modules.demo.drfFile.domain.DrfFile;
import org.jeecg.modules.demo.drfFile.service.DrfFileService;
import org.jeecg.modules.demo.drfIndividualReview.entity.DrfIndividualReview;
import org.jeecg.modules.demo.drfIndividualReview.service.IDrfIndividualReviewService;
import org.jeecg.modules.demo.drfNotice.entity.DrfNotice;
import org.jeecg.modules.demo.drfNotice.service.IDrfNoticeService;
import org.jeecg.modules.demo.drfProblem.entity.DrfProblem;
import org.jeecg.modules.demo.drfProblem.service.IDrfProblemService;
import org.jeecg.modules.demo.drfReviewAssignments.service.IDrfReviewAssignmentsService;
import org.jeecg.modules.demo.drfReviewOpinions.entity.DrfReviewOpinions;
import org.jeecg.modules.demo.drfReviewOpinions.service.IDrfReviewOpinionsService;
import org.jeecg.modules.demo.drfStudent.service.IDrfStudentService;
import org.jeecg.modules.demo.drfTecher.entity.DrfTeacher;
import org.jeecg.modules.demo.drfTecher.service.IDrfTeacherService;
import org.jeecg.modules.demo.drfpapers.entity.DrfPapers;
import org.jeecg.modules.demo.drfpapers.service.IDrfPapersService;
import org.jeecg.modules.demo.drfusers.entity.DrfUsers;
import org.jeecg.modules.demo.drfusers.service.IDrfUsersService;
import org.jeecg.modules.demo.pojo.*;
import org.jeecg.modules.demo.student.service.MinIOService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/drf/teacherPortal")
@Slf4j
@Api(tags="盲审—教师端")
public class teacherController {

    @Autowired
    private IDrfUsersService drfUsersService;
    @Autowired
    private MinIOService minIOService;
    @Autowired
    private IDrfPapersService drfPapersService;
    @Autowired
    private IDrfReviewAssignmentsService drfReviewAssignmentsService;
    @Autowired
    private IDrfReviewOpinionsService drfReviewOpinionsService;
    @Autowired
    private IDrfIndividualReviewService drfIndividualReviewService;
    @Autowired
    private IDrfNoticeService drfNoticeService;
    @Autowired
    private DrfFileService drfFileService;
    @Autowired
    private IDrfTeacherService drfTeacherService;
    @Autowired
    private IDrfStudentService drfStudentService;
    @Autowired
    private IDrfProblemService drfProblemService;


    /**
     * 添加教师信息
     */
    @ApiOperation("添加(修改)教师信息")
    @GetMapping("/addTeacher")
    public Result<String> addTeacher(teacherDTO teacherDTO) {
        String userId = String.valueOf(BaseContext.getCurrentId());
        DrfUsers drfUsers = drfUsersService.getById(userId);
        if (!drfUsers.getStatus().equals("teacher")) {
            return Result.error("请先登录教师账号");
        }

        DrfTeacher drfTeacher = new DrfTeacher();
        BeanUtils.copyProperties(teacherDTO, drfTeacher);
        drfTeacher.setUserId(userId);
        drfTeacherService.updateById(drfTeacher);
        if(teacherDTO.getPhone() != null){
            drfUsers.setPhone(teacherDTO.getPhone());
            drfUsers.setUpdatedTime(DateTime.now());
            drfUsersService.updateById(drfUsers);
        }

        return Result.success("添加(修改)成功");
    }



    /**
     * 文件下载
     */
    @ApiOperation("文件下载")
    @GetMapping("/download/{id}")
    public Result<fileUrlVO> download(@PathVariable String id) {//id为文件表id
        //判断是否为教师
        String userId = String.valueOf(BaseContext.getCurrentId());
        DrfUsers drfUsers = drfUsersService.getById(userId);
        if (!drfUsers.getStatus().equals("teacher")) {
            return Result.error("请先登录教师账号");
        }
        log.info("文件下载 : 文件表" +  id);
        //根据id查询论文，获取文件表
        DrfFile drfFile = drfFileService.getById(id);
        if (drfFile == null){
            return Result.error("文件不存在");
        }
        String bucketName = drfFile.getBucketName();
        fileUrlVO fileUrlVo = new fileUrlVO();
        fileUrlVo.setPaperName(drfFile.getPaperName());//论文名
        String paperURL = minIOService.getPresignedUrl(drfFile.getPaperFile(), bucketName,3600);
        fileUrlVo.setPaperURL(paperURL);//论文
        log.info("获取到paperURL  " + paperURL);
        fileUrlVo.setSupportingName(drfFile.getSupportingName());//支持材料名
        fileUrlVo.setSupportingURL(minIOService.getPresignedUrl(drfFile.getSupportingFile(), bucketName,3600));//支持材料
        fileUrlVo.setPlagiarismCheckName(drfFile.getPlagiarismCheckName());//查重文件名
        fileUrlVo.setPlagiarismCheckURL(minIOService.getPresignedUrl(drfFile.getPlagiarismCheckFile(), bucketName,3600));//查重
        fileUrlVo.setProgramName(drfFile.getProgramName());//培养方案名
        fileUrlVo.setProgramURL(minIOService.getPresignedUrl(drfFile.getProgramFile(), bucketName,3600));//培养方案
        return Result.success(fileUrlVo);
    }

    /**
     * 获取需要确认评审的论文数
     */
    @ApiOperation("获取需要确认评审与待提交意见的论文数")
    @GetMapping("/getReviewCount")
    public Result<int[]> getNeedReviewCount() {
        //根据教师id获取需要确认评审的论文数
        String Id = String.valueOf(BaseContext.getCurrentId());
        DrfUsers drfUsers = drfUsersService.getById(Id);
        if (!drfUsers.getStatus().equals("teacher")) {
            return Result.error("请先登录教师账号");
        }
        int[] paperCount = new int[2];
        Integer needReviewCount = drfReviewAssignmentsService.getNeedReviewCount(Id);
        Integer waitingForReviewCount = drfReviewAssignmentsService.getWaitingForReviewCount(Id);
        paperCount[0] = needReviewCount;//需要确认
        paperCount[1] = waitingForReviewCount;//待提交


        return Result.success(paperCount);
    }

//    /**
//     * 获取待提交意见的论文数
//     */
//    @ApiOperation("获取待提交意见的论文数")
//    @GetMapping("/getWaitingForReviewCount")
//    public Result<Integer> getWaitingForReviewCount() {
//        //根据教师id获取待提交意见的论文数
//        String Id = String.valueOf(BaseContext.getCurrentId());
//        DrfUsers drfUsers = drfUsersService.getById(Id);
//        if (!drfUsers.getStatus().equals("teacher")) {
//            return Result.error("请先登录教师账号");
//        }
//        Integer count = drfReviewAssignmentsService.getWaitingForReviewCount(Id);
//        return Result.success(count);
//    }

    /**
     * 获取需要确认评审的论文列表
     */
    @ApiOperation("获取需要确认评审的论文列表")
    @GetMapping("/getNeedReviewPapers")
    public Result<List<paperVO>> getNeedReviewPapers() {
        //根据教师id获取需要确认评审的论文列表id
        String Id = String.valueOf(BaseContext.getCurrentId());
        List<String> ids = drfReviewAssignmentsService.getNeedReviewPapers(Id);
        //如果ids为空，直接返回空列表
        if (ids == null || ids.isEmpty()) {
            return Result.success(new ArrayList<>());
        }
        //根据id集合查看论文列表
        List<DrfPapers> drfPapers = drfPapersService.listByIds(ids);
        List<paperVO> paperVOS = new ArrayList<>();
        for (DrfPapers drfPaper : drfPapers) {
            paperVO paperVO = new paperVO();
            BeanUtils.copyProperties(drfPaper, paperVO);
            paperVOS.add(paperVO);
        }
        return Result.success(paperVOS);
    }

    /**
     * 修改论文状态为同意或驳回
     */
    @ApiOperation("修改论文状态为同意或驳回")
    @Transactional
    @GetMapping("/updatePaperStatus/{paperId}")
    public Result<String> updatePaperStatus(@PathVariable String paperId, String status) {
        //获取用户id
        String userId = String.valueOf(BaseContext.getCurrentId());
        //修改审核任务表中的论文状态
        Boolean update = drfReviewAssignmentsService.updatePaperStatus(paperId, status, userId);
        if (drfReviewAssignmentsService.getStatusCount(paperId) && status.equals(papersStatus.REVIEW)){
            //若两个老师都同审核才修改论文状态
            drfPapersService.updatePaperStatus(paperId, status);
        }
        if (update != null && update && status.equals(papersStatus.REVIEW)){
            //成功修改且为同意审核
            //先创建审核意见表
            DrfReviewOpinions drfReviewOpinions = new DrfReviewOpinions();
            drfReviewOpinions.setPaperId(paperId);
            drfReviewOpinions.setTeacherId(userId);
            drfReviewOpinionsService.save(drfReviewOpinions);
            String opinionsId = drfReviewOpinions.getId();
            log.info("创建审核意见表成功，id为：{}", opinionsId);
            //再创建个人审核表
            DrfIndividualReview drfIndividualReview = new DrfIndividualReview();
            drfIndividualReview.setPapersId(paperId);
            drfIndividualReview.setTeacherId(userId);
            drfIndividualReview.setReviewOpinionsId(opinionsId);
            drfIndividualReview.setCreateTime(new Date());
            drfIndividualReviewService.save(drfIndividualReview);
            log.info("创建个人审核表成功，id为：{}", drfIndividualReview.getId());
            return Result.success("修改成功");
        }else if (update != null && update && status.equals(papersStatus.REJECT)){
            return Result.success("修改成功");
        }else if (update == null) {
            //修改失败
            return Result.error("修改失败，未找到对应论文");
        }else {
            //修改失败
            return Result.error("修改失败");
        }
    }

    /**
     * 获取待提交意见的论文列表
     */
    @ApiOperation("获取待提交意见的论文列表")
    @GetMapping("/getWaitingForReviewPapers")
    public Result<List<paperVO>> getWaitingForReviewPapers() {
        String userId = String.valueOf(BaseContext.getCurrentId());
        List<DrfPapers> papers = drfReviewAssignmentsService.getWaitingForReviewPapers(userId);
        //如果papers为空，直接返回空列表
        if (papers == null || papers.isEmpty()) {
            return Result.success(new ArrayList<>());
        }
        List<paperVO> paperVOS = papers.stream().map(paper -> {
            paperVO paperVO = new paperVO();
            paperVO.setId(paper.getId());//论文id
            paperVO.setTitle(paper.getTitle());
            paperVO.setContent(paper.getContent());
            paperVO.setUpdateTime(paper.getUpdateTime());//上传日期
            paperVO.setFileId(paper.getFileId());//存入文件表id
            paperVO.setDirection(paper.getDirection());//论文方向
            paperVO.setOpinionsId(drfReviewOpinionsService.getOpinionsId(paper.getId(), userId));
            return paperVO;
        }).collect(Collectors.toList());
        return Result.success(paperVOS);
    }

    /**
     * 获取历史论文列表
     */
    @ApiOperation("获取历史论文列表")
    @GetMapping("/getHistoryPapers")
    public Result<List<paperVO>> getHistoryPapers() {
        String userId = String.valueOf(BaseContext.getCurrentId());
        List<DrfPapers> papers = drfPapersService.getHistoryPapers(userId);
        log.info("获取历史论文列表");
        if (papers == null || papers.isEmpty()) {
            return Result.success(new ArrayList<>());
        }
        List<paperVO> paperVOS = papers.stream().map(paper -> {
            paperVO paperVO = new paperVO();
           BeanUtils.copyProperties(paper, paperVO);
           paperVO.setOpinionsId(drfReviewOpinionsService.getOpinionsId(paper.getId(), userId));
           paperVO.setEndTime(drfIndividualReviewService.getEndTime(paper.getId(), userId));
            return paperVO;
        }).collect(Collectors.toList());

        return Result.success(paperVOS);
    }

    /**
     * 接收公告
     */
    @ApiOperation("接收公告")
    @GetMapping("/teacherNotice")
    public Result<List<DrfNotice>> teacherNotice() {
        String userId = String.valueOf(BaseContext.getCurrentId());
        DrfUsers drfUsers = drfUsersService.getById(userId);
        if (!drfUsers.getStatus().equals("teacher")) {
            return Result.error("请先登录教师账号");
        }
        log.info("教师端请求公告");
        return Result.success(drfNoticeService.teacherNotice());
    }

    /**
     * 审核完毕
     */
    @Transactional
    @ApiOperation("审核完毕")
    @GetMapping("/reviewEnd/{id}")
    public Result<String> reviewEnd(@PathVariable String id) {
        String userId = String.valueOf(BaseContext.getCurrentId());
        if (!drfUsersService.getById(userId).getStatus().equals("teacher")) {
            return Result.error("请先登录教师账号");
        }
        //修改审核任务表为审核结束
        Boolean flag = drfReviewAssignmentsService.updateStatus(id, userId ,papersStatus.REVIEW_END);
        //修改个人审核表
        DrfIndividualReview drfIndividualReview = drfIndividualReviewService.getByPaperId(id);
        drfIndividualReview.setEndTime(new Date());
        drfIndividualReviewService.updateById(drfIndividualReview);

        //查询该论文的审核任务是否全部结束
        int count = drfReviewAssignmentsService.getCountByPaperId(id);
        if(count == 2){
            //修改论文表为审核结束
            drfPapersService.updateStatus(id, papersStatus.REVIEW_END);
        }
        return Result.success("审核完毕");
    }

}
